package com.eboss.sbs.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.eboss.sbs.R;
import com.eboss.sbs.activity.base.BaseActivity;
import com.eboss.sbs.activity.base.MainTabActivity;
import com.eboss.sbs.config.Config;
import com.eboss.sbs.enums.EnumConsts;
import com.eboss.sbs.http.API;
import com.eboss.sbs.http.HttpCallback;
import com.eboss.sbs.model.ActivateSubmitEntity;
import com.eboss.sbs.model.LoginEntity;
import com.eboss.sbs.model.UpgradeEntity;
import com.eboss.sbs.myapplication.MyApplication;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.security.Base64;
import com.mytools.tool.utils.AppDownLoadUtil;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.SharedUtil;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.SystemUtil;
import com.wosai.upay.bean.UpayOrder.PayModel;
import com.wosai.upay.bean.UpayResult;
import com.wosai.upay.common.DebugConfig;
import com.wosai.upay.common.UpayCallBack;
import com.wosai.upay.common.UpayTask;
import com.wosai.upay.http.Env;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class SplashActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{
	
	private int login_state = EnumConsts.UpgradeState.UNKNOWN.getType();  //-1 为判断更新状态   0非强制更新  1强制更新 2不需要更新
	
	private UpayTask upayTask;

	private static final String TAG = "Check";
	private static final int RC_CAMERA_PERM = 123;
	private static final int RC_LOCATION_CONTACTS_PERM = 124;
	private static final int RC_SETTINGS_SCREEN = 125;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mActivity = this;
		setContentView(R.layout.activity_splash);
		super.onCreate(savedInstanceState);



		requestPermissions();
	}

	private void requestPermissions() {
		//要获取的权限
		String[] perms = {
				Manifest.permission.ACCESS_COARSE_LOCATION,
				Manifest.permission.WRITE_EXTERNAL_STORAGE,
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.READ_PHONE_STATE,
				Manifest.permission.CALL_PHONE,
				Manifest.permission.CAMERA,

		};
		if (EasyPermissions.hasPermissions(this, perms)) {
			// Have permissions, do the thing!
//			Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
			initSqbSDK();
			checkUpgrade();
		} else {
			// Ask for both permissions
			EasyPermissions.requestPermissions(this, getString(R.string.ask_again),
					RC_LOCATION_CONTACTS_PERM, perms);
		}
	}
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		Log.e(TAG, "onRequestPermissionsResult:" );
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		Log.e(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
		initSqbSDK();
		checkUpgrade();
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		Log.e(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());
//		EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
//				getString(R.string.ask_again),
//				R.string.setting, R.string.cancel, perms);
		if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
			new AppSettingsDialog.Builder(this, getString(R.string.ask_again))
					.setTitle(getString(R.string.title_settings_dialog))
					.setPositiveButton(getString(R.string.setting))
					.setNegativeButton(getString(R.string.cancel), null /* click listener */)
					.setRequestCode(RC_SETTINGS_SCREEN)
					.build()
					.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RC_SETTINGS_SCREEN) {
			// Do something after user returned from app settings screen, like showing a Toast.
			Toast.makeText(this, R.string.returned_from_app_settings_to_activity, Toast.LENGTH_SHORT)
					.show();
		}
	}

	private void initSqbSDK() {
		upayTask = UpayTask.getInstance();
		DebugConfig.setDebug(Config.SQB_IS_DEBUG);//默认为非调试模式,如果需要调试,请设置为 true,打印和保存相关日志
		upayTask.initUpay(this, true, Env.UrlType.PRO);
	}
	
	private void checkUpgrade(){
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("types", Config.UPGRADE_CODE);
		API.http_post_2(this, API.UPGRADE, params, new HttpCallback<UpgradeEntity>(this, false) {
			@Override
			public void onSuccess(int statusCode, UpgradeEntity data) {
				int versionCode = data.getVersions();
				String url = data.getDown_url();
				final int mustUpdate = data.getMustUpdate();
				String message = data.getMessage();
				
				Integer nowVersion = SystemUtil.getVerCode(SplashActivity.this);
				
				if (versionCode > nowVersion) {
					login_state = (mustUpdate==0)? EnumConsts.UpgradeState.UPGRADE_UNFORCE.getType(): EnumConsts.UpgradeState.UPGRADE_FORCE.getType();
					AppDownLoadUtil update=new AppDownLoadUtil(SplashActivity.this, url, mustUpdate==0?false:true, new AppDownLoadUtil.AppDownLoadCallback() {
						@Override
						public void appDownloadFinish(int type) {
							if(type==AppDownLoadUtil.TYPE_CANCEL){
								if(mustUpdate==1){android.os.Process.killProcess(android.os.Process.myPid());}
								else{autoLogin();}
							}else if(type == AppDownLoadUtil.TYPE_FAIL){
								autoLogin();
							}
						}
					});
					update.showUpdateNoticeDialog(StringUtil.isNull(message)?"检测到新版本，请及时更新！":message);
				}
				else{
					login_state= EnumConsts.UpgradeState.LATEST.getType();
					autoLogin();
				}

			}
			
			@Override
			public void onFailure(int statusCode, String message) {
				autoLogin();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<UpgradeEntity>() {
				};
			}
		});
		
	}
	
	private void autoLogin(){
		
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				boolean isFirstTime = MyApplication.getmInstance().shareUtil.getShareBooleanPara(SharedUtil.SHARE_OPEN_FIRSTTIME, true);
				if(isFirstTime){
					startActivity(new Intent(SplashActivity.this, GuideActivity.class));
					finish();
				}
				else{
					String username = MyApplication.getmInstance().shareUtil.getShareStringPara(LoginActivity.LOGIN_USERNAME, "");
					String password = MyApplication.getmInstance().shareUtil.getShareStringPara(LoginActivity.LOGIN_PASSWORD, "");
					if(!StringUtil.isNull(username)&&!StringUtil.isNull(password)){
						login_request(username, password);
					}
					else{
						startActivity(new Intent(SplashActivity.this, LoginActivity.class));
						finish();
					}
				}
			}
		}, 1000);
		
	}
	
	private void login_request(final String username, final String password){
		LocalParasUtils.removeXLoginFlag(mActivity);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userName", username);
		params.put("password", Base64.getBase64(password));
		
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
		String imei = tm.getDeviceId();
		params.put("terminalSn", imei);
		
		API.http_post(this, API.LOGON, params, new HttpCallback<LoginEntity>(this, false) {
			@Override
			public void onSuccess(int statusCode, LoginEntity data) {
				//Log.e("2222: ", data.toString());
				MyApplication.getmInstance().setLoginEntity(data);
				MyApplication.getmInstance().shareUtil.setShareStringPara(LoginActivity.LOGIN_USERNAME, username); //保存登录UserName
				MyApplication.getmInstance().shareUtil.setShareStringPara(LoginActivity.LOGIN_PASSWORD, password); //保存登录UserName
				
				LocalParasUtils.saveXLoginDate(mActivity);	//设置最后登录时间
				
				//当返回扫码支付方式是富友时，不再进行激活处理
				int scanPayType = data.getScanPayType();
				if(scanPayType== EnumConsts.ScanPayType.FUYOU.getType()){
					gotoMainPage();
					finish();
					return;
				}
				
				boolean hasActivated = LocalParasUtils.checkActivateStatus(mActivity);
				String xActivityCode = LocalParasUtils.getActivateCode(mActivity);
				String nActivityCode = data.getActivateCode();
				
				if(hasActivated&&!StringUtil.isNull(nActivityCode)&&nActivityCode.equals(xActivityCode)){
					gotoMainPage();
				}
				else{
					if(StringUtil.isNull(nActivityCode)){gotoMainPage();}
					else{
						LocalParasUtils.removeActivateStatus(mActivity);
						activite(nActivityCode);
					}
				}
			}
			
			@Override
			public void onFailure(int statusCode, String message) {
				MyApplication.getmInstance().shareUtil.removeSharePara(LoginActivity.LOGIN_PASSWORD);
				startActivity(new Intent(SplashActivity.this, LoginActivity.class));
				finish();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<LoginEntity>() {
				};
			}
		});
	}
	
	/**
	 * 激活终端
	 * @param code
	 */
	private void activite(final String code){
		String vendor_id = "";//服务商 ID
		String vendor_key = "";//服务商 KEY
		try {
			ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(),PackageManager.GET_META_DATA);
			vendor_id = appInfo.metaData.getString("com.sqb.vendor_id");
			vendor_key = appInfo.metaData.getString("com.sqb.vendor_key");
		} catch (Exception e) {
			Toast.makeText(this, "未配置收钱吧ID与KEY", Toast.LENGTH_SHORT).show();
		}
		
		/**
		* activate 激活
		* @param code 激活码
		* @param vendor_id 服务商 ID
		* @param vendor_key 服务商 KEY 
		* @param payModel 支付模式
		* @param callBack 请求回调
		*/
		upayTask.activate(code, vendor_id, vendor_key, PayModel.NO_UI, new UpayCallBack() {
			@Override
			public void onExecuteResult(UpayResult result) {
				String RESULT_CODE = result.getResult_code();
				if(!StringUtil.isNull(RESULT_CODE)&&RESULT_CODE.equals("ACTIVATE_SUCCESS")){
					submit_after_actvate(code, 1);
				}
				else{
					LocalParasUtils.removeActivateStatus(SplashActivity.this);
					submit_after_actvate(code, 0);
				}
			}
		});
	}
	
	/**
	 * 向服务器返回激活结果
	 * @param code	激活码
	 * @param isSuccess	0失败  1成功
	 */
	private void submit_after_actvate(final String code, final int isSuccess){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", MyApplication.getmInstance().getLoginEntity().getSid());
		params.put("activateCode", code);
		params.put("isSuccess", isSuccess);
		API.http_post(this, API.ACTIVATE_SUBMIT, params, new HttpCallback<ActivateSubmitEntity>(this, false) {
			
			@Override
			public void onSuccess(int statusCode, ActivateSubmitEntity data) {
				LocalParasUtils.removeActivateStatus(mActivity);
				if(isSuccess==1){
					LocalParasUtils.saveActivateCode(mActivity, code);
					LocalParasUtils.saveMerchantNo(mActivity, data.getMerchantNo());
					LocalParasUtils.saveMerchantName(mActivity, data.getMerchantName());
					LocalParasUtils.saveTerminalName(mActivity, data.getTerminalName());
				}
				gotoMainPage();
			}
			
			@Override
			public void onFailure(int statusCode, String message) {
				LocalParasUtils.removeActivateStatus(mActivity);
				gotoMainPage();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<ActivateSubmitEntity>() {};
			}
		});
	}
	
	private void gotoMainPage(){
		startActivity(new Intent(SplashActivity.this, MainTabActivity.class));
		finish();
	}

}
